<!-- 跟投分配规则 新增-->
<template>
  <div>
	 <el-breadcrumb separator="/" class="bread-title">
	    <el-breadcrumb-item :to="{ path: '/investmentDistributionRule'}">跟投分配规则</el-breadcrumb-item>
	    <el-breadcrumb-item>{{pageType=='add'?'新增':'编辑'}}</el-breadcrumb-item>
	 </el-breadcrumb>
  	 <el-steps :active="active" :space="600" finish-status="success" style="margin:40px 200px">
	    <el-step title="跟投分配总比例设置"></el-step>
	    <el-step title="定向分配占比详情配置"></el-step>
	    <el-step title="预览"></el-step>
	 </el-steps>
	 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~step1~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
	 <div v-show="active == 1">
		  <el-form :model="ruleForm" ref="ruleform" label-width="140px" class="demo-ruleForm">
		      <el-form-item label="规则名称：" prop="name" >
		          <el-input v-model.trim="ruleForm.name" placeholder="请输入跟投分配规则名称"  maxlength="20"  style="width: 400px;"></el-input>
		      </el-form-item>
		      <el-form-item label="跟投类型：" prop="type" >
					<el-radio-group v-model="ruleForm.type" @change="clearcache" :disabled="openFlag==1">
					  <el-radio :label="0">定向</el-radio>
					  <el-radio :label="1">募集</el-radio>
					  <el-radio :label="2">定向+募集</el-radio>
					</el-radio-group>
			  </el-form-item>
			  <el-form-item label="定向跟投分配占比：" prop="directionalProportion" >
			      <el-input :disabled="ruleForm.type==1"  v-model="ruleForm.directionalProportion" placeholder="请输入定向跟投分配占比" step='0.01' maxlength="20" type="number" style="width: 400px;" @input.native="checkNum(ruleForm.directionalProportion,'directionalProportion')"></el-input>%
			  </el-form-item>
			  <el-form-item label="募集跟投分配占比：" prop="raiseProportion" >
			      <el-input :disabled="ruleForm.type==0" step='0.01' v-model="ruleForm.raiseProportion" placeholder="请输入募集跟投分配占比" @input.native="checkNum(ruleForm.raiseProportion,'raiseProportion')"  maxlength="20" type="number" style="width: 400px;"></el-input>%
			  </el-form-item>
		  </el-form>
		  <div style="margin:60px 200px">
			  <el-button type="primary" style="margin-top: 12px;" @click="next">下一步</el-button>
			  <el-button type="primary" style="margin-top: 12px;" @click="cancelhander">取消</el-button>
		  </div>
	  </div>
	  <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~step2~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
	  <div v-show="active == 2">
			<el-form :model="ruleForm" ref="ruleform" label-width="140px" class="demo-ruleForm">
				<el-form-item label="业务线：" prop="line">
				    <el-select v-model="ruleForm.line" filterable style="width: 400px;">
				        <el-option v-for="item in blinelist"
				                   :key="item.id"
				                   :label="item.businessLineName"
				                   :value="item.id">
				        </el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="比例:" prop="businessProportion" >
				    <el-input v-model="ruleForm.businessProportion"  placeholder="请输入比例" type="number" step='0.01'  @input.native="checkNum(ruleForm.businessProportion,'businessProportion')"  style="width: 400px;"></el-input>%
				</el-form-item>

				<el-button type="primary" style="margin: 20px 20%" @click="addline">添加</el-button>
				<hr/>

				<!-- 业务线 -->
				<div class="linewrapper">
					<ul>
						<li v-for="(item,index) in teamlist"> 
							<p>
								<span style="margin-right: 20px">业务线：{{item.businessName}}({{item.businessProportion}}%) </span>
								<el-button type="text"  @click="delline(item)">删除</el-button>
								<el-button type="primary" size="small" @click="newgrade(item)">新建职级</el-button>
								<el-table v-if="item.distributionDetailList && item.distributionDetailList.length>0" :data="item.distributionDetailList" style="width:70%;margin-top: 15px;" border>
								    <el-table-column label="部门名称" prop="departmentName" align="center">
								    </el-table-column>
								    <el-table-column label="职级" prop="rankName"  align="center">
								    </el-table-column>
								    <el-table-column label="绝对值%" prop="rankMagnitude" align="center">
								    </el-table-column>
								    <el-table-column label="操作" align="center">
									   <template slot-scope='scope'>
											<el-button type="text" @click="fn('edit',scope.row,item)">编辑</el-button>
											<el-button type="text" @click="fn('del',scope.row)">删除</el-button>
										</template>
								    </el-table-column>
								</el-table>
							</p>
						</li>
					</ul>
				</div>
			</el-form>

			<div style="margin:60px 200px">
			    <el-button type="primary" style="margin-top: 12px;" @click="prev">上一步</el-button>
			    <el-button type="primary" style="margin-top: 12px;" @click="next">下一步</el-button>
			</div>
	    </div>
	   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~step3~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
		<div v-show="active == 3">
			<h3>跟投分配比例设置</h3>
			<hr>
			<p>规则名称：{{ruleForm.name}}</p>
			<p>*跟投类型：{{initType(ruleForm.type)}}</p>
			<p v-if="ruleForm.type !==1">定向跟投分配占比：{{ruleForm.directionalProportion}}%</p>
			<p>募集跟投分配占比：{{ruleForm.raiseProportion?ruleForm.raiseProportion:0}}%</p>

			<h3  v-if="ruleForm.type !==1">内部员工跟投分配比例详情</h3>
			<hr>
			<el-table :data="previewArr" border   v-if="ruleForm.type !==1"
			:span-method="objectSpanMethod" highlight-current-row
			:summary-method="getSummaries"
			show-summary
			 >
			    <el-table-column  type="index" prop="type" label="序号" width="50" align="center"></el-table-column>
			    <el-table-column  label="业务线" prop="businessName"  align="center">
			    </el-table-column>
			    <el-table-column label="占比（业务线）%" prop="businessProportion" align="center">
			    </el-table-column>
			    <el-table-column label="比例（部门）%" prop="departmentProportion" align="center">
			    </el-table-column>
			    <el-table-column label="部门" prop="departmentName" align="center">
			    </el-table-column>
			    <el-table-column label="职级" prop="rankName" align="center"></el-table-column>
			    <el-table-column label="比例（职级）%" prop="rankProportion" align="center"></el-table-column>
			    <el-table-column label="绝对值（职级）%" prop="rankMagnitude" align="center"></el-table-column>
			</el-table>

			<div style="margin:60px 200px">
			    <el-button style="margin-top: 12px;" type="primary" @click="prev">上一步</el-button>
			    <el-button style="margin-top: 12px;" type="primary" @click="save">保存</el-button>
			    <el-button style="margin-top: 12px;" type="primary" @click="cancelhander">取消</el-button>
			</div>
	   </div>
       <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~新建职级~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
		<el-dialog
		  :title="ranktype=='edit'? '编辑':'新建'"
		  :visible.sync="centerDialogVisible"
		  width="26%"
		  center>
		  <div>
			<p>业务线：&nbsp;&nbsp;{{currentline.businessName}}</p>
			<p>部门：&nbsp;&nbsp;&nbsp;
				<el-select v-model="ruleForm2.depart" filterable style="width: 300px;" @change="departchange">
				    <el-option v-for="item in departlist"
				               :key="item.id"
				               :label="item.departmentName"
				               :value="item.id">
				    </el-option>
				</el-select>
			</p>
			<p>职级：&nbsp;&nbsp;&nbsp;
				<el-select v-model="ruleForm2.rank" filterable style="width: 300px;">
				    <el-option v-for="item in stationslist"
				               :key="item.id"
				               :label="item.stationName"
				               :value="item.id">
				    </el-option>
				</el-select>
			</p>
			<p>绝对值：
				<el-input v-model="ruleForm2.avalue" type="number" placeholder="请输入绝对值"  maxlength="20"  style="width: 300px;" step='0.01'  @input.native="checkNum(ruleForm2.avalue,'avalue')" ></el-input>
			</p>
		  </div>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="centerDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="newgradesave">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>
<script>

	import api from '@/api/apiPath'
	export default {
	    data() {
	        return {
				  active: 1,
				  pageType:'',
				  ruleForm:{
				  	name:'',//规则名称
				  	type:2,//跟投类型
				  	directionalProportion:undefined,//定向占比
				  	raiseProportion:undefined,//募集占比
				  	line:undefined,//业务线
				  	businessProportion:undefined,//比例
				  },
				  centerDialogVisible: false,
				  blinelist:[],
				  teamlist:[], //当前展示的所有数据
				  currentline:{},//当前业务线的数据
				  //新增职级相关data
				  ruleForm2:{
				  	avalue:undefined,//绝对值
				  	depart:undefined,//部门
				  	rank:undefined,//职级
				  },
				  ranktype:'add',//职级弹框类型 add 新增 eidt编辑
				  currentrank:{},//当前职级
				  departlist:[],//部门list
				  stationslist:[],
				  //预览相关data
				  previewArr:[],//预览
				  spanArr: [],//二维数组，用于存放单元格合并规则
				  position: 0,//用于存储相同项的开始index
				  id:undefined,//编辑时获取数据
				  openFlag:undefined,//0 未开启过 1开启过
	        }
	    },
	    created() {
	    	this.pageType = this.$route.query.pageType
	    	this.id = this.$route.query.id
	    	this.allbusinessline()
	    	if(this.pageType =='edit'){
	    		this.getinfodata()
	    	}
	    },
	    methods: {
	    	// 转换数据
	    	convert (array) {
				    let bidArr = []
				    let newArray = []
				    array.forEach((curArr,index) => {
				    	if (!curArr.businessId) return
				        if(bidArr.indexOf(curArr.businessId) > -1) {
				        	for(let i in newArray){
				        		if (curArr.businessId==newArray[i]['businessId']) 
				        			newArray[i]['distributionDetailList'].push(curArr)
				        	}
				        }else{
				        	bidArr.push(curArr.businessId)
				        	let obj ={}
				        	obj['businessId'] = curArr['businessId']
				        	obj['businessName'] = curArr['businessName']
				        	obj['businessProportion'] = curArr['businessProportion']
				        	obj['distributionDetailList'] =[]	
				        	obj['distributionDetailList'].push(curArr)
				        	newArray.push(obj)
				        }
				    })
				    return newArray
			},
	    	//编辑是获取详情信息
	    	getinfodata(){
	    		this.axios.get(api.DISTRIBUTTIONVIEW+this.id).then(res=>{
	    		  if (res.data.code == 200) {
	    		  		let idata = res.data.data
	    		  		this.ruleForm.name = idata.name
	    		  		this.ruleForm.type = idata.type
	    		  		this.ruleForm.directionalProportion = idata.directionalProportion
	    		  		this.ruleForm.raiseProportion = idata.raiseProportion
	    		  		this.openFlag = idata.openFlag
	    		  		this.teamlist = this.convert(idata.distributionDetailList)
	    		  		//需要虚拟id 用于表格合并和排序
	    		  		for(let i in this.teamlist){
	    		  			for(let j in  this.teamlist[i].distributionDetailList){
	    		  				let orderNum =  this.teamlist[i].distributionDetailList[j]['departmentId']+''+this.teamlist[i].distributionDetailList[j]['businessId']
	    		  				this.$set(this.teamlist[i].distributionDetailList[j],'order',orderNum)
	    		  			}
	    		  		}
	    		  }
	    	   })
	    	},
	    	getSummaries(param) {
				return ["合计", ,100,,,,,100];
	    	},
	    	initType(val){
	    	  if (val == 0) {
	    	    return '定向'
	    	  }else if (val == 1) {
	    	     return '募集'
	    	  }else if (val == 2) {
	    	    return '定向+募集'
	    	  }
	    	},
	    	rowspan(idx, prop) {
	    	  this.spanArr[idx] = [];
	    	  this.position = 0; 
	    	  let len = 0; 
	    	  this.previewArr.forEach((item,index) => {
	    	    if( index === 0){
	    	      this.spanArr[idx].push(1);      
	    	      this.position = 0;
	    	    }else{
	    	      if(this.previewArr[index][prop] === this.previewArr[index-1][prop] ){
	    	        this.spanArr[idx][this.position] += 1;//有相同项
	    	        this.spanArr[idx].push(0); // 名称相同后往数组里面加一项0
	    	      }else{
	    	        this.spanArr[idx].push(1);//同列的前后两行单元格不相同
	    	        this.position = index;
	    	      }
	    	    }
	    	  })
	    	},
	    	  //表格单元格合并
	    	objectSpanMethod({ row, column, rowIndex, columnIndex }) {
	    	    for(let i = 1; i<5; i++) {
	    	      if(columnIndex === i &&  this.spanArr.length>0){
	    	         const _row = this.spanArr[i][rowIndex];
	    	         const _col = _row>0 ? 1 : 0;
	    	         return {
	    	           rowspan: _row,
	    	           colspan: _col
	    	         }
	    	      }
	    	    }
	    	 },
	    	allbusinessline(){
	    		this.axios.get(api.DISTRIBUTIONALLBUSINESSLINE).then(res=>{
	    			if (res.data.code == 200) {
	    				this.blinelist = res.data.data
	    			}
	    		})
	    	},
	    	clearcache(){
	    		this.ruleForm.raiseProportion = ''
	    		this.ruleForm.directionalProportion = ''
	    		if(this.ruleForm.type == 0){
	    			this.ruleForm.directionalProportion =100
	    		}else if(this.ruleForm.type == 1){
	    			this.ruleForm.raiseProportion =100
	    		}
	    	},
	    	checkNum(val,type){
	    	    let value = (val.toString().match(/^\d*(\.?\d{0,2})/g)[0])
	    	    this.$nextTick(()=>{
		    	    if (type !== 'avalue') {
						this.ruleForm[type] = value
		    	    }else {
		    	    	this.ruleForm2.avalue = value
		    	    }
	    	    })	
	    	},
	    	//业务线中职级的编辑删除
	    	fn(type,val,item){
	    		this.ranktype = type
              if (type == 'edit') {
              		this.currentrank = val
              		//编辑打开的时候展示
					this.ruleForm2.rank = val.rankId
					this.ruleForm2.avalue = val.rankMagnitude 
					//编辑需要重新获取当前业务线下部门list和职级列表
					this.currentline = item
					this.ruleForm2.depart = val.departmentId
					this.getdepartlist()
					this.getstationslist(this.ruleForm2.depart)
					this.centerDialogVisible = true

              }else if(type == 'del'){
              	this.$confirm('确定删除?', '提示', {
              	     confirmButtonText: '确定',
              	     cancelButtonText: '取消',
              	     type: 'warning'
              	   }).then(() => {              	     
              	     this.teamlist.forEach((item,index)=>{
              	     	item.distributionDetailList.forEach((item2,index2)=>{
              	     		if (item2.departmentId == val.departmentId && item2.rankId == val.rankId) {
              	     			this.teamlist[index]['distributionDetailList'].splice(index2,1)
              	     		}
              	     	})
              	     })
              	   }).catch(() => {
              	     this.$message({
              	       type: 'info',
              	       message: '已取消'
              	     });          
              	   });
              }
	    	},
	    	addline(){
	    		if (!this.ruleForm.line) {
	    			this.$message({
	    			    message: '请选择业务线',
	    			    type: 'warning'
	    			});
	    			return 
	    		}
	    		if(!this.ruleForm.businessProportion){
	    			this.$message({
	    			    message: '请输入比例',
	    			    type: 'warning'
	    			});
	    			return 
	    		}
	    		if (this.ruleForm.businessProportion > +this.ruleForm.directionalProportion) {
					this.$message({
					    message: '业务线比例不得大于定向跟投分配占比',
					    type: 'warning'
					});
					return 	
	    		}
	    		if (this.ruleForm.businessProportion == 0) {
	    			this.$message({
	    			    message: '业务线比例需大于0',
	    			    type: 'warning'
	    			});
	    			return 	
	    		}

				//业务线不能重复添加
				let number = 0
				for(let value of this.teamlist){
					if (value['businessId'] == this.ruleForm.line) {
						this.$message({
						    message: '该业务线已存在，请重新选择',
						    type: 'warning'
						});
						return 
					}
					//业务线比例之和定向跟投分配占比
					number += +value['businessProportion'] 
					if (number + +this.ruleForm.businessProportion> +this.ruleForm.directionalProportion) {
						this.$message({
						    message: '业务线比例之和为定向跟投分配占比',
						    type: 'warning'
						});
						return 
					}
				}
				//获取添加当前业务线下的字段
				let tempdata = this.blinelist.find(item=>{
					return item.id == this.ruleForm.line
				});

				//添加业务线
				this.teamlist.push({
					'businessId':tempdata.id,
					'businessName':tempdata.businessLineName,
					'businessProportion':this.ruleForm.businessProportion,
					'distributionDetailList':[]
				})
				//添加之后清除缓存 
				this.ruleForm.line = ''
				this.ruleForm.businessProportion = ''
	    	},
	    	cancelhander(){
	    		this.$router.go(-1)
	    	},
	    	prev(){
	    		//募集返回上一页
	    		if (this.ruleForm.type ==1 ) {
	    			this.active = 1
	    			return
	    		}
	    		this.active-- 
	    	},

			next() {
				if (this.active == 1) {
					if (this.ruleForm.name == '') {
						this.$message({
						    message: '请输入跟投分配规则名称',
						    type: 'warning'
						});
						return 
					}
					//定向
					if (this.ruleForm.type ==0) {
						if (this.ruleForm.directionalProportion == '') {
							this.$message({
							    message: '请输入定向跟投分配占比',
							    type: 'warning'
							});
							return 
						}
						if (Number(this.ruleForm.directionalProportion) !== 100) {
							this.$message({
							    message: '定向跟投分配占比为100%',
							    type: 'warning'
							});
							return 
						}
					}else if(this.ruleForm.type ==1){
						if (this.ruleForm.raiseProportion == '') {
							this.$message({
							    message: '请输入募集跟投分配占比',
							    type: 'warning'
							});
							return 
						}
						if (Number(this.ruleForm.raiseProportion) !== 100) {
							this.$message({
							    message: '募集跟投分配占比为100%',
							    type: 'warning'
							});
							return 
						}

						// //募集没有业务线
						// this.active = 3
						// return
					}else if(this.ruleForm.type == 2){
						if (typeof this.ruleForm.directionalProportion == 'undefined') {
							this.$message({
							    message: '请输入定向跟投分配占比',
							    type: 'warning'
							});
							return 
						}
						if (typeof this.ruleForm.raiseProportion == 'undefined') {
							this.$message({
							    message: '请输入募集跟投分配占比',
							    type: 'warning'
							});
							return
						}
						if (Number(this.ruleForm.raiseProportion) + Number(this.ruleForm.directionalProportion) !== 100) {
							this.$message({
							    message: '定向跟投分配占比+募集跟投分配占比为100%',
							    type: 'warning'
							});
							return
						}
					}

					// 检索规则名是否重复
					this.axios.post(api.DISTRIBUTIONSELECTNAME,{id:this.id,name:this.ruleForm.name}).then((res) => {
						if (res.data.code == 200) {
							if (this.ruleForm.type !== 1) {
								this.active++
							}else{
								this.active = 3
							}	
						}
					}).catch(res2=>{
						if (res2.data.code !== 200) {
						// 	this.$message({
						// 	    message: '规则名不能重复',
						// 	    type: 'warning'
						// 	});
							return
						}
					})

				}else if (this.active == 2) {
					if (this.teamlist.length == 0) {
						this.$message({
						    message: '请选择业务线',
						    type: 'warning'
						});
						return
					}
					let bool= false
					for (let item of this.teamlist){
						if (item.distributionDetailList.length>0) {
							bool = true
							break
						}
					}
					if (!bool) {
						this.$message({
						    message: '请新建业务线职级',
						    type: 'warning'
						});
						return
					}

					this.previewArr=[]
					let pobj={}//放置id相同的职级之和
					for(let val1 of this.teamlist){
						 let bid = val1['businessId']
						 val1['distributionDetailList'].sort(this.compare('order'))
						 for(let val2 of val1['distributionDetailList']){
							let obj = {}
							let ranknum = ((val2.rankMagnitude/val1.businessProportion)*100).toFixed(2)
							obj.rankMagnitude = val2.rankMagnitude//职级绝对值
							obj.rankName= val2.rankName//职级名称
							obj.rankId = val2.rankId
							obj.departmentName= val2.departmentName//部门名称
							obj.departmentId= val2.departmentId//部门ID
							obj.businessProportion=val1.businessProportion//业务线比例
							obj.businessName= val1.businessName//业务线名称
							obj.businessId= val1.businessId//businessId	
							obj.rankProportion = ranknum//职级比例
							obj.order = val2.order
							// obj.departId = val2.departId//编辑界面用于排序
							let _id = val2.departmentId
						    let _num = Number(ranknum)
							if(!pobj[bid]){
							   pobj[bid] = {}
							}
							if (!pobj[bid][_id]) {
							   pobj[bid][_id] =_num
							}else {
							   //同业务线 同部门比例职级相加
							    pobj[bid][_id] +=_num
							}
							this.previewArr.push(obj)
						}
					}

					let rNum = 0
					for(let idx1 in this.previewArr){
						rNum += Number(this.previewArr[idx1]['rankMagnitude'])
						for(let idx2 in pobj){
							if(this.previewArr[idx1]['businessId'] == idx2){
								this.previewArr[idx1]['departmentProportion'] = pobj[idx2][this.previewArr[idx1]['departmentId']].toFixed(2)
							}
						}
					}

					//绝对值之和是否和定向比例相等 浮点运算精度丢失
	 				if (parseFloat(this.ruleForm.directionalProportion).toFixed(2)  !== parseFloat(rNum).toFixed(2)) {
	 					this.$message({
	 					    message: '绝对值之和需和定向跟投分配占比相等',
	 					    type: 'warning'
	 					});
	 					return false
					}
					//追加募集数据 用于展示入库前要删除
					if (this.ruleForm.type !==0) {
						let robj ={}
						robj['businessName'] ="募集"
						robj['businessProportion'] = this.ruleForm.raiseProportion
						robj['businessId']  = '-'
						robj['departmentId'] = '-'
						robj['departmentName']  = '-'
						robj['departmentProportion'] = '-'
						robj['rankId']  = '-'
						robj['rankMagnitude'] = this.ruleForm.raiseProportion
						robj['rankName']  = '-'
						robj['rankProportion'] = Number(this.ruleForm.raiseProportion).toFixed(2)
						this.previewArr.push(robj)
					}
					this.rowspan(1,'businessId')
					this.rowspan(2,'businessId')
					this.rowspan(3,'order')
					this.rowspan(4,'order')

					this.active++
				}
			},

			//根据数组中部门id 排序 否则合并表格会出现问题
			compare(prop){
				return function(a, b){
					let value1 = a[prop]
					let value2 = b[prop]
					return value1 -value2
				}
			},
			save(){
				//删除掉募集的数据
				if (this.ruleForm.type !==0) {
					this.previewArr.pop()
				}
				let tempobj ={}
				tempobj['name'] =this.ruleForm.name
				tempobj['type'] = this.ruleForm.type
				tempobj['directionalProportion'] = this.ruleForm.directionalProportion
				tempobj['raiseProportion'] = this.ruleForm.raiseProportion
				tempobj['distributionDetailList'] = this.previewArr
				let url
				if (this.pageType == 'edit') {
					 url =api.DISTRIBUTIONUPDATE
					 tempobj['id'] = this.id
				}else {
					 url =api.DISTRIBUTIONCREATE
				}
				this.axios.post(url,tempobj).then(res=>{
					if (res.data.code == 200) {
						this.$message({
						    message: this.pageType == 'edit'?'编辑成功':'新增成功',
						    type: 'success'
						});
						this.$router.push({path:'/investmentDistributionRule'})
					}
				})
			},
			//新建职级
			newgrade(val){
				this.ranktype = 'add'
				this.ruleForm2.avalue = ''
				this.ruleForm2.depart = ''
				this.ruleForm2.rank = ''
				this.currentline =val
				this.centerDialogVisible = true
				this.getdepartlist()//部门list
			},
			//职级依赖部门id
			departchange(val){
				this.ruleForm2.rank =''
				this.getstationslist(val)//职级list
			},
			getstationslist(val){
				this.axios.get(api.DISTRIBUTIONSTATIONS+this.currentline.businessId+'/'+val).then(res=>{
					if (res.data.code == 200) {
						this.stationslist = res.data.data
					}
				})
			},
			getdepartlist(){
				this.axios.get(api.DISTRIBUTIONDEPARTMENT+this.currentline.businessId).then(res=>{
					if (res.data.code == 200) {
						this.departlist = res.data.data
					}
				})
			},
			//新建、编辑、删除职务保存
			newgradesave(){
				if (this.ruleForm2.depart == '') {
					this.$message({
					    message: '请选择部门',
					    type: 'warning'
					});
					return 
				}
				if (this.ruleForm2.rank == '') {
					this.$message({
					    message: '请选择职级',
					    type: 'warning'
					});
					return 
				}
				if (this.ruleForm2.avalue == '') {
					this.$message({
					    message: '请输入绝对值',
					    type: 'warning'
					});
					return 	
				}

				//获取所选部门下字段
				let tempdata1 = this.departlist.find(item=>{
					return item.id ==  this.ruleForm2.depart
				});
				//职级下字段
				let tempdata2 = this.stationslist.find(item=>{
					return item.id ==  this.ruleForm2.rank
				});

				//新建职级
				if(this.ranktype  == 'add'){
					// 部门id 职级id 同时存在的时候判重 🤔 
					for (let item of this.teamlist){
						if (item['businessId'] == this.currentline.businessId){
							if (+item.businessProportion < +this.ruleForm2.avalue) {
								this.$message({
								    message: '绝对值不能大于该业务线所占比例',
								    type: 'warning'
								});
								return
							}
							if (item['distributionDetailList'].length>0) {
								let num =0
							    for (let item2 of item['distributionDetailList']){
							    	if (item2.departmentId == this.ruleForm2.depart && item2.rankId == this.ruleForm2.rank) {
							    		this.$message({
										    message: '已存在该部门、该职级的数据',
										    type: 'warning'
										});
										return
							    	}
							    	num += Number(item2.rankMagnitude)
								 }
								 if (num + +this.ruleForm2.avalue > +item.businessProportion) {
									this.$message({
									    message: '绝对值相加之和不能大于该业务线所占比例',
									    type: 'warning'
									});
									return
								 }
							}
						}
					}
					//把部门职级数据添加当前业务线中
					for(let index in this.teamlist){
						if (this.teamlist[index]['businessId'] == this.currentline.businessId) {
							let obj = {}
							obj['departmentName'] = tempdata1.departmentName
							obj['departmentId'] = tempdata1.id
							obj['rankName'] = tempdata2.stationName
							obj['rankId']= tempdata2.id
							obj['rankMagnitude'] = this.ruleForm2.avalue
							obj['id']= this.teamlist[index]['distributionDetailList'].length+1
							obj['order'] = tempdata1.id+''+this.teamlist[index]['businessId']//用于合并表格
							this.teamlist[index]['distributionDetailList'].push(obj)
						}
					}
				//编辑职级
				}else if(this.ranktype=='edit'){
					for(let index in this.teamlist){
						if (this.teamlist[index]['businessId'] == this.currentline.businessId){
							if (this.teamlist[index]['distributionDetailList'].length>0) {
								for(let index2 in this.teamlist[index]['distributionDetailList']){
                                    if (this.teamlist[index]['distributionDetailList'][index2].id == this.currentrank.id) {
										//遍历当前业务线下部门列表 和当前id不相等是否已存在相同的职级、部门id
										for(let val of this.teamlist[index]['distributionDetailList']){
												if ( val.id !== this.currentrank.id) {
													if (val.departmentId == tempdata1.id && val.rankId == tempdata2.id ) {
														this.$message({
														    message: '已存在该部门、该职级的数据',
														    type: 'warning'
														});
														return
													}
												}
										 }
                                    	let obj = {}
                                    	obj['departmentName'] = tempdata1.departmentName
                                    	obj['departmentId'] = tempdata1.id
                                    	//编辑当前职级的时候需要拿到departId
                                    	obj['order'] = tempdata1.id+''+ this.currentline.businessId
                                    	obj['rankName'] = tempdata2.stationName
                                    	obj['rankId']= tempdata2.id
                                    	obj['rankMagnitude'] = this.ruleForm2.avalue
                                    	obj['id'] = this.currentrank.id
                                    	this.$set(this.teamlist[index]['distributionDetailList'],index2, obj)
                                    }
								}
							}
						}
					}
				}
				this.centerDialogVisible = false
			},
			//删除业务线
			delline(val){
				this.$confirm('确定删除该业务线?', '提示', {
				     confirmButtonText: '确定',
				     cancelButtonText: '取消',
				     type: 'warning'
				   }).then(() => {              	     
				     this.teamlist.forEach((item,index)=>{
				     	if (item.businessId == val.businessId) {
				     		this.teamlist.splice(index,1)
				     	}
				     })
				   }).catch(() => {
				     this.$message({
				       type: 'info',
				       message: '已取消'
				     });          
				   });
			}
	    }
	}
</script>

<style lang="stylus">
	.linewrapper ul
		list-style: none
		
</style>